<template>
  <div class="logs-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="page-title">操作日志</div>
      <div class="header-actions">
        <el-button @click="exportLogs">导出日志</el-button>
        <el-button type="primary" @click="fetchLogs">刷新</el-button>
      </div>
    </div>

    <!-- 筛选区域 -->
    <el-card shadow="hover" class="filter-card">
      <template #header>
        <div class="card-header">
          <span>日志筛选</span>
          <div class="header-actions">
            <el-button size="small" @click="resetFilter">重置</el-button>
            <el-button size="small" type="primary" @click="handleFilter">查询</el-button>
          </div>
        </div>
      </template>
      <el-form :model="filterForm" :inline="true" size="default">
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="filterForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 380px;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="用户">
          <el-input v-model="filterForm.username" placeholder="请输入用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="filterForm.actionType" placeholder="请选择操作类型" clearable>
            <el-option label="登录" value="login"></el-option>
            <el-option label="登出" value="logout"></el-option>
            <el-option label="查询" value="query"></el-option>
            <el-option label="新增" value="create"></el-option>
            <el-option label="修改" value="update"></el-option>
            <el-option label="删除" value="delete"></el-option>
            <el-option label="导出" value="export"></el-option>
            <el-option label="导入" value="import"></el-option>
            <el-option label="预测" value="predict"></el-option>
            <el-option label="系统" value="system"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作模块">
          <el-select v-model="filterForm.module" placeholder="请选择操作模块" clearable>
            <el-option label="客户管理" value="customer"></el-option>
            <el-option label="预测管理" value="prediction"></el-option>
            <el-option label="模型管理" value="model"></el-option>
            <el-option label="系统设置" value="settings"></el-option>
            <el-option label="用户管理" value="user"></el-option>
            <el-option label="角色管理" value="role"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日志级别">
          <el-select v-model="filterForm.logLevel" placeholder="请选择日志级别" clearable>
            <el-option label="INFO" value="info"></el-option>
            <el-option label="WARNING" value="warning"></el-option>
            <el-option label="ERROR" value="error"></el-option>
            <el-option label="DEBUG" value="debug"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 日志表格 -->
    <el-card shadow="hover" class="logs-table-card">
      <el-table 
        v-loading="loading" 
        :data="logData" 
        border 
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <el-table-column prop="timestamp" label="操作时间" width="180" sortable></el-table-column>
        <el-table-column prop="username" label="操作用户" width="120"></el-table-column>
        <el-table-column prop="action" label="操作类型" width="120">
          <template #default="scope">
            <el-tag 
              :type="getActionTagType(scope.row.action)"
              effect="plain"
            >
              {{ getActionName(scope.row.action) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="module" label="操作模块" width="120">
          <template #default="scope">
            <el-tag effect="plain">{{ getModuleName(scope.row.module) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="日志级别" width="100">
          <template #default="scope">
            <el-tag
              :type="getLevelTagType(scope.row.level)"
              effect="dark"
              size="small"
            >
              {{ scope.row.level?.toUpperCase() || 'INFO' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="IP地址" width="140"></el-table-column>
        <el-table-column prop="description" label="操作描述" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="viewLogDetails(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog 
      v-model="logDetailsVisible" 
      title="日志详情" 
      width="60%"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="操作时间">{{ currentLog.timestamp }}</el-descriptions-item>
        <el-descriptions-item label="操作用户">{{ currentLog.username }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <el-tag :type="getActionTagType(currentLog.action)" effect="plain">
            {{ getActionName(currentLog.action) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作模块">
          <el-tag effect="plain">{{ getModuleName(currentLog.module) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="日志级别">
          <el-tag :type="getLevelTagType(currentLog.level)" effect="dark" size="small">
            {{ currentLog.level?.toUpperCase() }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ currentLog.ip }}</el-descriptions-item>
        <el-descriptions-item label="操作描述" :span="2">{{ currentLog.description }}</el-descriptions-item>
        <el-descriptions-item label="浏览器" :span="2">{{ currentLog.userAgent }}</el-descriptions-item>
        <el-descriptions-item label="请求方法" v-if="currentLog.method">{{ currentLog.method }}</el-descriptions-item>
        <el-descriptions-item label="请求路径" v-if="currentLog.path">{{ currentLog.path }}</el-descriptions-item>
      </el-descriptions>

      <div class="log-details-content" v-if="currentLog.requestBody || currentLog.responseBody">
        <el-tabs>
          <el-tab-pane label="请求参数" v-if="currentLog.requestBody">
            <pre class="json-content">{{ formatJson(currentLog.requestBody) }}</pre>
          </el-tab-pane>
          <el-tab-pane label="响应结果" v-if="currentLog.responseBody">
            <pre class="json-content">{{ formatJson(currentLog.responseBody) }}</pre>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div class="log-stack-trace" v-if="currentLog.stackTrace">
        <h4>错误堆栈</h4>
        <pre>{{ currentLog.stackTrace }}</pre>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserLogs, exportLogs as apiExportLogs } from '@/api/modules/system'

// 加载状态
const loading = ref(false)

// 筛选表单
const filterForm = reactive({
  timeRange: [],
  username: '',
  actionType: '',
  module: '',
  logLevel: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 日志数据
const logData = ref([])

// 日志详情对话框
const logDetailsVisible = ref(false)
const currentLog = reactive({})

// 获取日志数据
const fetchLogs = async () => {
  loading.value = true

  try {
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      username: filterForm.username || '',
      action: filterForm.actionType || '',
      start_date: filterForm.timeRange?.[0] ? filterForm.timeRange[0].split(' ')[0] : '',
      end_date: filterForm.timeRange?.[1] ? filterForm.timeRange[1].split(' ')[0] : ''
    }

    const response = await getUserLogs(params)

    if (response.results) {
      // DRF分页响应
      logData.value = response.results.map(log => ({
        id: log.id,
        timestamp: log.created_at,
        username: log.username_display,
        actionType: log.action,
        module: '系统',
        level: 'info',
        ip: log.ip_address || '',
        description: log.details || '',
        userAgent: log.user_agent || ''
      }))
      pagination.total = response.count || 0
    } else {
      logData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取日志失败:', error)
    ElMessage.error('获取日志失败')
    logData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}



// 获取操作类型对应的标签类型
const getActionTagType = (action) => {
  const typeMap = {
    login: 'success',
    logout: 'info',
    query: '',
    create: 'success',
    update: 'warning',
    delete: 'danger',
    export: 'info',
    import: 'warning',
    predict: 'success',
    system: 'info'
  }
  return typeMap[action] || ''
}

// 获取操作名称
const getActionName = (action) => {
  const nameMap = {
    login: '登录',
    logout: '登出',
    query: '查询',
    create: '新增',
    update: '修改',
    delete: '删除',
    export: '导出',
    import: '导入',
    predict: '预测',
    system: '系统'
  }
  return nameMap[action] || action
}

// 获取模块名称
const getModuleName = (module) => {
  const nameMap = {
    customer: '客户管理',
    prediction: '预测管理',
    model: '模型管理',
    settings: '系统设置',
    user: '用户管理',
    role: '角色管理'
  }
  return nameMap[module] || module
}

// 获取日志级别对应的标签类型
const getLevelTagType = (level) => {
  const typeMap = {
    info: 'info',
    warning: 'warning',
    error: 'danger',
    debug: ''
  }
  return typeMap[level] || ''
}

// 格式化JSON
const formatJson = (json) => {
  try {
    if (typeof json === 'string') {
      json = JSON.parse(json)
    }
    return JSON.stringify(json, null, 2)
  } catch (e) {
    return json
  }
}

// 查看日志详情
const viewLogDetails = (log) => {
  Object.assign(currentLog, log)
  logDetailsVisible.value = true
}

// 导出日志
const exportLogs = async () => {
  try {
    const params = {
      username: filterForm.username || '',
      action: filterForm.actionType || '',
      start_date: filterForm.timeRange?.[0] ? filterForm.timeRange[0].split(' ')[0] : '',
      end_date: filterForm.timeRange?.[1] ? filterForm.timeRange[1].split(' ')[0] : '',
      limit: 10000
    }

    const response = await apiExportLogs(params)

    if (response.success) {
      // 创建下载链接
      const data = response.data
      const csvContent = [
        ['ID', '用户名', '操作类型', '详细信息', 'IP地址', '创建时间'].join(','),
        ...data.map(log => [
          log.id,
          log.username,
          log.action,
          `"${log.details || ''}"`,
          log.ip_address || '',
          log.created_at
        ].join(','))
      ].join('\n')

      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.setAttribute('href', url)
      link.setAttribute('download', `logs_${new Date().toISOString().split('T')[0]}.csv`)
      link.style.display = 'none'

      try {
        document.body.appendChild(link)
        link.click()
      } finally {
        // 延迟清理，避免DOM操作冲突
        setTimeout(() => {
          try {
            if (link.parentNode) {
              document.body.removeChild(link)
            }
            URL.revokeObjectURL(url)
          } catch (cleanupError) {
            console.warn('清理下载链接失败:', cleanupError)
          }
        }, 100)
      }

      ElMessage.success(`成功导出 ${data.length} 条日志`)
    } else {
      ElMessage.error(response.error || '导出日志失败')
    }
  } catch (error) {
    console.error('导出日志失败:', error)
    ElMessage.error('导出日志失败')
  }
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.timeRange = []
  filterForm.username = ''
  filterForm.actionType = ''
  filterForm.module = ''
  filterForm.logLevel = ''
  fetchLogs()
}

// 应用筛选
const handleFilter = () => {
  pagination.currentPage = 1
  fetchLogs()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchLogs()
}

// 处理每页数量变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchLogs()
}

// 生命周期钩子
onMounted(() => {
  fetchLogs()
})
</script>

<style lang="scss" scoped>
.logs-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    align-items: center;
    
    .page-title {
      font-size: 22px;
      font-weight: bold;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .filter-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .logs-table-card {
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  .log-details-content {
    margin-top: 20px;
    
    .json-content {
      background-color: #f5f7fa;
      padding: 10px;
      border-radius: 4px;
      overflow-x: auto;
      font-family: monospace;
      max-height: 300px;
      overflow-y: auto;
    }
  }
  
  .log-stack-trace {
    margin-top: 20px;
    
    h4 {
      color: #f56c6c;
      margin-top: 0;
      margin-bottom: 10px;
    }
    
    pre {
      background-color: #f5f7fa;
      padding: 10px;
      border-radius: 4px;
      overflow-x: auto;
      font-family: monospace;
      color: #f56c6c;
      max-height: 200px;
      overflow-y: auto;
    }
  }
}
</style> 